package server;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

import logic.Message;

import java.sql.ResultSet;



public class DB_Manager {

	private Connection DB;
	private OBL_Server server;

	public DB_Manager(Connection dB_Connection,OBL_Server server) {
		DB = dB_Connection;
		this.server = server;
	}

		
	/**
	 * This function query the DB and returns a ResultSet with the query result
	 * Use this function only for SELECT - do not update the DB here (it is not synchronized)
	 * @param query - the DB query
	 * @return ResultSet containing the query result
	 */
	public ResultSet Query(String query){
		Statement stmt;
		try 
		{
			stmt = DB.createStatement();
			ResultSet rs = stmt.executeQuery(query);
			//stmt.close();-will close rs
			return rs;

		}catch(SQLException e){
			server.Log("[DB.Query] - exception on query: " + query);
			return null;
		}
	}
	
	/**
	 * This functions query the database, and returns the generated auto increment value.
	 * It is used only for Inserting values where primary key is auto-incremented
	 * @param query - the DB query
	 * @return the generated value, or -1 for failure
	 */
	public int QueryAutoIncrement(String query){
		PreparedStatement stmt;
		try 
		{
			stmt = DB.prepareStatement(query);
			stmt.executeUpdate(query, PreparedStatement.RETURN_GENERATED_KEYS);
			DB.setAutoCommit(false);
			DB.commit();
			DB.setAutoCommit(true);
			ResultSet rs = stmt.getGeneratedKeys();
			rs.next();
			int value = rs.getInt(1);
			rs.close();
			stmt.close();
			
			return value;
			
		}catch(SQLException e){
			server.Log("[DB.QueryAutoIncrement] - exception on query: " + query);
			return -1;
		}

	}
	
	/**
	 * This function is called for when changed needed to be made on the DB
	 * and therefore it is synchronized.
	 * @param query - the string to update/insert/delete on the DB
	 * @return 1 for success, 0 otherwise
	 */
	public int Update(String query){
		try{
			PreparedStatement update = DB.prepareStatement(query);
			update.executeUpdate();
			update.close();
			return 1;
		}catch (SQLException e){
			server.Log("[DB.Update] - exception on query: " + query);
			return 0;
		}		
		
	}
	
}

